<template>
  <div class="logistics-center-container">
    <!-- 筛选区域 -->
    <el-card class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams">
        <el-form-item label="操作类型">
          <el-select v-model="queryParams.operationType" clearable placeholder="请选择操作类型">
            <el-option v-for="item in operationTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号">
          <el-input v-model="queryParams.logisticsId" clearable placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="queryParams.productName" clearable placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" clearable placeholder="请选择状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">筛选</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container">
      <el-table border :data="tableData" style="width: 100%">
        <el-table-column label="物流单号" prop="logisticsId" width="200" />
        <el-table-column label="操作类型" prop="operationType" width="100" />
        <el-table-column label="商品名称" prop="productName" width="150" />
        <el-table-column label="数量" prop="quantity" width="80" />
        <el-table-column label="源仓库" prop="sourceWarehouseLabel" width="150" />
        <el-table-column label="目的地/去向" prop="destination" width="180" />
        <el-table-column label="关联单号" prop="orderNo" width="180" />
        <el-table-column label="操作时间" prop="timestamp" width="180" />
        <el-table-column label="状态" prop="status" width="120">
          <template slot-scope="scope">
            <el-tag :type="statusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <!-- 添加操作列 -->
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-dropdown trigger="click" @command="(command) => handleStatusChange(scope.row, command)">
              <el-button size="small" type="text">
                更新状态<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-for="status in getAvailableNextStatus(scope.row.status, scope.row.operationType)"
                  :key="status"
                  :command="status"
                >
                  {{ status }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button size="small" type="text" @click="handleViewDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :current-page.sync="pagination.currentPage"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 物流详情弹窗 -->
    <el-dialog title="物流详情" :visible.sync="detailDialog.visible" width="600px">
      <el-descriptions border :column="1">
        <el-descriptions-item label="物流单号">{{ detailDialog.currentRow.logisticsId }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">{{ detailDialog.currentRow.operationType }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ detailDialog.currentRow.productName }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ detailDialog.currentRow.quantity }}</el-descriptions-item>
        <el-descriptions-item label="源仓库">{{ detailDialog.currentRow.sourceWarehouseLabel }}</el-descriptions-item>
        <el-descriptions-item label="目的地/去向">{{ detailDialog.currentRow.destination }}</el-descriptions-item>
        <el-descriptions-item label="关联单号">{{ detailDialog.currentRow.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ detailDialog.currentRow.timestamp }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="statusTagType(detailDialog.currentRow.status)">{{ detailDialog.currentRow.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="detailDialog.currentRow.statusHistory && detailDialog.currentRow.statusHistory.length > 0" label="状态历史">
          <div v-for="(history, index) in detailDialog.currentRow.statusHistory" :key="index" class="status-history-item">
            <el-tag size="small" :type="statusTagType(history.status)">{{ history.status }}</el-tag>
            <span class="status-time">{{ history.time }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item v-if="detailDialog.currentRow.remarks" label="备注">
          {{ detailDialog.currentRow.remarks }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'LogisticsCenter',
  data() {
    return {
      queryParams: {
        operationType: '',
        logisticsId: '',
        productName: '',
        status: '',
      },
      operationTypeOptions: [
        { value: '出库', label: '出库' },
        { value: '调拨', label: '调拨' },
        { value: '退货', label: '退货' },
      ],
      statusOptions: [
        { value: '运输中', label: '运输中' },
        { value: '分拣中', label: '分拣中' },
        { value: '派送中', label: '派送中' },
        { value: '已到货', label: '已到货' },
        { value: '已签收', label: '已签收' },
        { value: '退货中', label: '退货中' },
        { value: '已退回', label: '已退回' },
      ],
      // 状态流转规则
      statusFlowRules: {
        '出库': {
          '运输中': ['分拣中', '派送中', '已到货'],
          '分拣中': ['派送中', '已到货'],
          '派送中': ['已到货', '已签收'],
          '已到货': ['已签收'],
          '已签收': []
        },
        '调拨': {
          '运输中': ['分拣中', '已到货'],
          '分拣中': ['已到货'],
          '已到货': ['已签收'],
          '已签收': []
        },
        '退货': {
          '退货中': ['分拣中', '已退回'],
          '分拣中': ['已退回'],
          '已退回': []
        }
      },
      originalLogisticsData: [], // 从localStorage加载的原始数据
      tableData: [], // 当前页显示的数据
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      // 添加详情弹窗数据
      detailDialog: {
        visible: false,
        currentRow: {}
      }
    }
  },
  created() {
    this.loadLogisticsData()
  },
  mounted() {
    // 监听localStorage更新的事件
    window.addEventListener('storageUpdated', this.handleStorageUpdate);
    window.addEventListener('storage', this.handleDefaultStorageUpdate);
  },
  beforeDestroy() {
    window.removeEventListener('storageUpdated', this.handleStorageUpdate);
    window.removeEventListener('storage', this.handleDefaultStorageUpdate);
  },
  methods: {
    handleStorageUpdate(e) {
      if (e.detail && e.detail.key === 'logisticsCenterData') {
        this.loadLogisticsData();
      }
    },
    handleDefaultStorageUpdate(e) {
       if (e.key === 'logisticsCenterData') {
        this.loadLogisticsData();
      }
    },
    loadLogisticsData() {
      const data = localStorage.getItem('logisticsCenterData')
      this.originalLogisticsData = data ? JSON.parse(data) : []
      this.handleQuery() // 加载后立即应用筛选和分页
    },
    handleQuery() {
      let filteredData = [...this.originalLogisticsData]

      if (this.queryParams.operationType) {
        filteredData = filteredData.filter(item => item.operationType === this.queryParams.operationType)
      }
      if (this.queryParams.logisticsId) {
        filteredData = filteredData.filter(item => item.logisticsId && item.logisticsId.includes(this.queryParams.logisticsId))
      }
      if (this.queryParams.productName) {
        filteredData = filteredData.filter(item => item.productName && item.productName.includes(this.queryParams.productName))
      }
      if (this.queryParams.status) {
        filteredData = filteredData.filter(item => item.status === this.queryParams.status)
      }
      // 按时间倒序排列，新的在前
      filteredData.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());

      this.pagination.total = filteredData.length
      this.pagination.currentPage = 1 // 重置到第一页
      this.updateTableData(filteredData) // 将筛选排序后的数据传递给updateTableData
    },
    resetQuery() {
      this.queryParams = {
        operationType: '',
        logisticsId: '',
        productName: '',
        status: '',
      }
      this.handleQuery()
    },
    updateTableData(sourceData = this.originalLogisticsData) { // 接收筛选排序后的数据
       // 应用筛选逻辑，确保sourceData是已筛选和排序的数据
      let dataToPaginate = [...sourceData]; // 使用传入的已处理数据

      // 如果queryParams有值，则再次过滤 (handleQuery中已做，这里理论上sourceData已是最新)
      // 但为确保独立调用updateTableData时的正确性，可以保留或优化
      if (this.queryParams.operationType) {
        dataToPaginate = dataToPaginate.filter(item => item.operationType === this.queryParams.operationType);
      }
      if (this.queryParams.logisticsId) {
        dataToPaginate = dataToPaginate.filter(item => item.logisticsId && item.logisticsId.includes(this.queryParams.logisticsId));
      }
      if (this.queryParams.productName) {
        dataToPaginate = dataToPaginate.filter(item => item.productName && item.productName.includes(this.queryParams.productName));
      }
      if (this.queryParams.status) {
        dataToPaginate = dataToPaginate.filter(item => item.status === this.queryParams.status);
      }
      dataToPaginate.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());


      this.pagination.total = dataToPaginate.length; // 更新总数

      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      this.tableData = dataToPaginate.slice(start, end)
    },
    handleCurrentChange(page) {
      this.pagination.currentPage = page
      this.handleQuery() // 重新执行查询以获取正确分页数据
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.pagination.currentPage = 1
      this.handleQuery() // 重新执行查询以获取正确分页数据
    },
    statusTagType(status) {
      switch (status) {
        case '运输中':
          return 'primary';
        case '分拣中':
          return 'warning';
        case '派送中':
          return 'info';
        case '已到货':
          return 'success';
        case '已签收':
          return 'success';
        case '退货中':
          return 'danger';
        case '已退回':
          return 'danger';
        default:
          return 'info';
      }
    },
    // 获取可用的下一个状态
    getAvailableNextStatus(currentStatus, operationType) {
      if (!currentStatus || !operationType) return [];

      // 根据操作类型和当前状态获取可用的下一个状态
      const nextStatusList = this.statusFlowRules[operationType][currentStatus] || [];
      return nextStatusList;
    },
    // 处理状态变更
    handleStatusChange(row, newStatus) {
      // 找到对应的物流记录
      const index = this.originalLogisticsData.findIndex(item => item.logisticsId === row.logisticsId);
      if (index === -1) return;

      const logisticsItem = this.originalLogisticsData[index];

      // 如果没有状态历史，创建一个
      if (!logisticsItem.statusHistory) {
        logisticsItem.statusHistory = [];
      }

      // 添加当前状态到历史记录
      logisticsItem.statusHistory.push({
        status: logisticsItem.status,
        time: new Date().toLocaleString('zh-CN', { hour12: false })
      });

      // 更新状态
      logisticsItem.status = newStatus;

      // 保存到localStorage
      localStorage.setItem('logisticsCenterData', JSON.stringify(this.originalLogisticsData));

      // 刷新表格数据
      this.handleQuery();

      this.$message.success(`物流单 ${row.logisticsId} 状态已更新为 ${newStatus}`);
    },
    // 查看详情
    handleViewDetail(row) {
      this.detailDialog.currentRow = JSON.parse(JSON.stringify(row));
      this.detailDialog.visible = true;
    }
  },
}
</script>

<style lang="scss" scoped>
.logistics-center-container {
  padding: 20px;
}
.filter-container {
  margin-bottom: 20px;
}
.table-container {
  // styles for table container
}
.status-history-item {
  margin-bottom: 5px;
  display: flex;
  align-items: center;

  .status-time {
    margin-left: 10px;
    color: #909399;
    font-size: 12px;
  }
}
</style>
